/**
 * 新建/编辑表单页
 */
import React, { useState } from 'react';
import { Form, Input, Select, Upload, message, Button, Modal, Space } from 'antd';
import QuillEditor from 'react-quill';
import TextArea from 'antd/es/input/TextArea';
import { createNew } from '../../services/news';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import "react-quill/dist/quill.snow.css";

/** 表单类型校验 */
interface IFormData {
  title: string;
  imgUrl: string;
  description: string;
  type: string;
  author: string;
  content: string;
  /** 仅有产品拥有规格 */
  spec?: string;
}

interface IProps {
  data?: IFormData;
  open: boolean; // 是否展示
  status: 'create' | 'edit'; // 新建或者编辑
  type: 'news' | 'products' | 'publications';
  onModalFinish: () => void;
}

const EditorFormModal: React.FC<IProps> = ({
  data,
  open,
  status,
  type,
  onModalFinish
}) => {
  const [form] = Form.useForm();

  React.useEffect(() => {
    if (status === 'create') {
      form.resetFields();
    }
  }, [status, open]);

  React.useEffect(() => {
    if (data) {
      form.setFieldsValue({
        ...data
      });
    }
  }, [data]);

  const selectType = React.useMemo(() => {
    switch (type) {
      case 'news':
        return [{
          label: '科研动态',
          value: 'KEYAN',
        },
        {
          label: '合作交流',
          value: 'HEZUO',
        },
        {
          label: '团队生活',
          value: 'TUANDUI',
        },
        {
          label: '通知公告',
          value: 'TONGZHI',
        }
        ]
      case 'products':
        return [{
          label: '二维 TEC',
          value: 'TEC',
        },
        {
          label: 'RT-TEC',
          value: 'RT-TEC',
        },
        {
          label: 'TEC 预报图',
          value: 'PRE-TEC',
        },
        {
          label: '三维电子密度图',
          value: ''
        },
        {
          label: '单站 ROTI',
          value: 'ONE-SITE-ROTI',
        },
        {
          label: '全球 DTEC',
          value: 'GLOBAL-DTEC',
        },
        {
          label: '全球 ROTI',
          value: 'GLOBAL-ROTI',
        },
        {
          label: 'PPP',
          value: 'PPP'
        }
        ]
      case 'publications':
        return [{
          label: '代表性成果',
          value: 'DAIBIAO',
        },
        {
          label: '会议报告',
          value: 'HUIYI',
        },
        {
          label: '发明专利',
          value: 'FAMING',
        },
        {
          label: '软件登记',
          value: 'RUANJIAN',
        },
        {
          label: '出版专著',
          value: 'CHUBAN',
        },
        {
          label: '荣誉奖励',
          value: 'RONGYU',
        }
        ]
      default:
        return [];
    }
  }, [type]);
  const [content, setContent] = useState('');

  const onContentChange = (value: any) => {
    setContent(value);
  };

  const uploadProps = {
    name: 'file',
    action: 'http://example.com/upload', // 替换为你的上传地址
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  const onFinish = () => {
    const formValues = form.getFieldsValue();
    console.log('Received values of form: ', formValues);
    // 处理提交逻辑
    switch (type) {
      case 'news':
        createNew(formValues)
          .then(res => {
            message.success('创建成功');
          })
        break;
      case 'products':
        break;
      case 'publications':
        break;
      default:
    }
    // onModalFinish();
  };

  return (
    <Modal
      width={1400}
      open={open}
      onClose={onModalFinish}
      onCancel={onModalFinish}
      onOk={onFinish}
    >
      <Form
        labelCol={{
          span: 4
        }}
        style={{
          paddingTop: '24px'
        }}
        form={form}
        name="basic"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="标题"
          name="title"
          rules={[{ required: true, message: '请输入标题!' }]}
        >
          <Input placeholder="请输入标题" />
        </Form.Item>

        <Form.Item
          label="图片链接"
          name="imgUrl"
          rules={[{ required: true, message: '请输入图片链接!' }]}
        >
          <Input placeholder="请输入图片链接" />
        </Form.Item>

        <Form.Item
          label="描述"
          name="description"
          rules={[{ required: true, message: '请输入描述!' }]}
        >
          <TextArea rows={4} placeholder="请输入描述" />
        </Form.Item>

        <Form.Item
          label="类型"
          name="type"
          rules={[{ required: true, message: '请选择类型!' }]}
        >
          <Select placeholder="请选择类型" options={selectType} />
        </Form.Item>

        <Form.Item
          label="作者"
          name="author"
          rules={[{ required: true, message: '请输入作者!' }]}
        >
          <Input placeholder="请输入作者" />
        </Form.Item>

        <Form.Item
          label="内容"
          name="content"
          rules={[{ required: true, message: '请输入内容!' }]}
        >
          <QuillEditor
            value={content}
            onChange={onContentChange}
            modules={{
              toolbar: [
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ list: 'ordered' }, { list: 'bullet' }],
                ['link', 'image', 'video'],
                ['clean'],
              ],
            }}
          />
        </Form.Item>
        <Form.Item
          label="规格"
        >
          <Form.List
            name="spec"
            rules={[
              {
                validator: async (_, specs) => {
                  if (!specs || specs.length < 2) {
                    return Promise.reject(new Error('至少有两项'));
                  }
                },
              },
            ]}
          >
            {(fields, { add, remove }, { errors }) => (
              <>
                {fields.map((field, index) => (
                  <Space key={field.key}>
                    <Form.Item noStyle name={[field.name, 'spec']}>
                      <Input placeholder='spec' />
                    </Form.Item>
                    <Form.Item noStyle name={[field.name, 'value']}>
                      <Input placeholder='value' />
                    </Form.Item>
                  </Space>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    style={{ width: '60%' }}
                    icon={<PlusOutlined />}
                  >
                    Add field
                  </Button>
                  <Button
                    type="dashed"
                    onClick={() => {
                      add('The head item', 0);
                    }}
                    style={{ width: '60%', marginTop: '20px' }}
                    icon={<PlusOutlined />}
                  >
                    Add field at head
                  </Button>
                  <Form.ErrorList errors={errors} />
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form.Item>

        <Form.Item
          label="上传图片"
          name="images"
        >
          <Upload {...uploadProps}>
            <Button>
              Click to Upload
            </Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditorFormModal;